<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace backend\controllers;

use builder\base\BaseController;
use builder\helper\H5;
use builder\table\TableBuilder;
use common\models\Admin;
use common\models\EmailRecord;
use common\models\SmsRecord;

/**
 * 短信和邮件记录
 * @author cleverstone
 * @since ym2.0
 */
class RecordController extends BaseController
{
    public $actionVerbs = [
        'sms' => ['GET'],
        'sms-content' => ['GET'],
        'sms-delete' => ['POST'],

        'email' => ['GET'],
        'email-content' => ['GET'],
        'email-delete' => ['POST'],
    ];

    /**
     * 短信记录
     * @return string
     * @throws \Throwable
     */
    public function actionSms()
    {
        $userColumns = Admin::query(['username'])->indexBy('id')->column();
        $userColumns[0] = '⭐system';
        ksort($userColumns);

        $table = TableBuilder::instance(['id' => 'record_sms']);

        if ($this->isAjax) {
            $table->setColumnDependency($userColumns)
                ->setQuery(function () {
                    $params = $this->filteredGet;
                    $startAt = null;
                    $endAt = null;
                    if (!empty($params['create_at'])) {
                        list($startAt, $endAt) = array_map('trim', explode('/', $params['create_at']));
                    }

                    $query = SmsRecord::query();
                    $query->andFilterWhere([
                        'and',
                        [
                            'or',
                            // 短信种类
                            ['like', 'category', isset($params['keyword']) ? trim($params['keyword']) : null],
                            // 接收手机号
                            ['like', 'receive_mobile', isset($params['keyword']) ? $params['keyword'] : null],
                            // 短信内容
                            ['like', 'content', isset($params['keyword']) ? $params['keyword'] : null],
                        ],
                        ['sender' => isset($params['sender']) ? $params['sender'] : null],
                        ['between', 'created_at', $startAt, $endAt],
                    ]);

                    return $query;
                })
                ->setOrderBy(['id' => SORT_DESC])
                ->setColumns([
                    'id',
                    'category',
                    'code',
                    'sender' => function ($row, $dependency) {
                        return !empty($dependency[$row['sender']]) ? $dependency[$row['sender']] : '-';
                    },
                    'receive_mobile',
                    'created_at',
                ]);
        } else {
            $table->setTitle('短信记录')
                ->setTableHead([
                    $this->tableHead->field('id')->title('ID'),
                    $this->tableHead->field('category')->title('短信种类'),
                    $this->tableHead->field('code')->title('校验码'),
                    $this->tableHead->field('sender')->title('发送人'),
                    $this->tableHead->field('receive_mobile')->title('接收人'),
                    $this->tableHead->field('created_at')->title('发送时间'),
                    $this->tableHead->toolbar()->title('操作项')->width(120),
                ])
                ->setRowOperation([
                    $this->rowOperation->modal()->title('查看短信内容')->route('record/sms-content')->height(350)->closeBtn(),
                ])
                ->setToolbarCustom([
                    $this->toolbarCustom->ajax()->title('删除五个月以前')->route('record/sms-delete')->btnClass('layui-btn-danger')->method(),
                ])
                ->setToolbarFilter([
                    'keyword' => $this->toolbarFilter->text()->label('关键词')->placeholder('请输入')->uiClass('w-330'),
                    'sender' => $this->toolbarFilter->select()
                        ->label('发送人')
                        ->placeholder('请选择')
                        ->options($userColumns)
                        ->uiClass('w-330 mx-md-3'),
                    'create_at' => $this->toolbarFilter->datetime()->label('发送时间')->placeholder('请选择')->uiClass('w-330 mr-md-3'),
                ]);
        }

        return $table->render();
    }

    /**
     * 查看短信内容
     * @param int $id 短信记录ID
     * @return string
     * @throws \Throwable
     */
    public function actionSmsContent($id)
    {
        $detail = SmsRecord::query(['content'])->where(['id' => $id])->one();
        if (empty($detail)) {
            return $this->renderContentX(H5::alert('空', 'info'));
        }

        return $this->renderContentX(H5::text($detail['content'], ['class' => 'p-3 f13'], 'p'));
    }

    /**
     * 删除五个月前的短信记录
     * @return string
     */
    public function actionSmsDelete()
    {
        $lastFive = date('Y-m-d H:i:s', strtotime('-5 months'));
        $result = SmsRecord::deleteAll(['<=', 'created_at', $lastFive]);
        if ($result) {
            return $this->asOk('删除五月以前的【短信记录】成功, 删除数量:' . $result . '条');
        }

        return $this->asOk('五月以前【短信记录】为空, 不需要删除');
    }

    /**
     * 邮件记录
     * @return string
     * @throws \Throwable
     */
    public function actionEmail()
    {
        $userColumns = Admin::query(['username'])->indexBy('id')->column();
        $userColumns[0] = '⭐system';
        ksort($userColumns);

        $table = TableBuilder::instance(['id' => 'record_email']);

        if ($this->isAjax) {
            $table->setColumnDependency($userColumns)
                ->setQuery(function () {
                    $params = $this->filteredGet;
                    $startAt = null;
                    $endAt = null;
                    if (!empty($params['create_at'])) {
                        list($startAt, $endAt) = array_map('trim', explode('/', $params['create_at']));
                    }

                    $query = EmailRecord::query();
                    $query->andFilterWhere([
                        'and',
                        [
                            'or',
                            // 邮件种类
                            ['like', 'category', isset($params['keyword']) ? trim($params['keyword']) : null],
                            // 接收邮箱
                            ['like', 'receive_email', isset($params['keyword']) ? $params['keyword'] : null],
                            // 短信内容
                            ['like', 'content', isset($params['keyword']) ? $params['keyword'] : null],
                        ],
                        ['sender' => isset($params['sender']) ? $params['sender'] : null],
                        ['between', 'created_at', $startAt, $endAt],
                    ]);

                    return $query;
                })
                ->setOrderBy(['id' => SORT_DESC])
                ->setColumns([
                    'id',
                    'category',
                    'code',
                    'sender' => function ($row, $dependency) {
                        return !empty($dependency[$row['sender']]) ? $dependency[$row['sender']] : '-';
                    },
                    'receive_email',
                    'created_at',
                ]);
        } else {
            $table->setTitle('邮件记录')
                ->setTableHead([
                    $this->tableHead->field('id')->title('ID'),
                    $this->tableHead->field('category')->title('邮件种类'),
                    $this->tableHead->field('code')->title('校验码'),
                    $this->tableHead->field('sender')->title('发送人'),
                    $this->tableHead->field('receive_email')->title('接收邮箱'),
                    $this->tableHead->field('created_at')->title('发送时间'),
                    $this->tableHead->toolbar()->title('操作项')->width(120),
                ])
                ->setRowOperation([
                    $this->rowOperation->page()->title('查看邮箱内容')->route('record/email-content')->targetBlank(),
                ])
                ->setToolbarCustom([
                    $this->toolbarCustom->ajax()->title('删除五个月以前')->route('record/email-delete')->btnClass('layui-btn-danger')->method(),
                ])
                ->setToolbarFilter([
                    'keyword' => $this->toolbarFilter->text()->label('关键词')->placeholder('请输入')->uiClass('w-330'),
                    'sender' => $this->toolbarFilter->select()
                        ->label('发送人')
                        ->placeholder('请选择')
                        ->options($userColumns)
                        ->uiClass('w-330 mx-md-3'),
                    'create_at' => $this->toolbarFilter->datetime()->label('发送时间')->placeholder('请选择')->uiClass('w-330 mr-md-3'),
                ]);
        }

        return $table->render();
    }

    /**
     * 查看邮件内容
     * @param int $id 邮件记录ID
     * @return string
     * @throws \Throwable
     */
    public function actionEmailContent($id)
    {
        $detail = EmailRecord::query(['content'])->where(['id' => $id])->one();
        if (empty($detail)) {
            return $this->renderContentX(H5::alert('空', 'info'));
        }

        return $detail['content'];
    }

    /**
     * 删除五个月前的邮件记录
     * @return string
     */
    public function actionEmailDelete()
    {
        $lastFive = date('Y-m-d H:i:s', strtotime('-5 months'));
        $result = EmailRecord::deleteAll(['<=', 'created_at', $lastFive]);
        if ($result) {
            return $this->asOk('删除五月以前的【邮件记录】成功, 删除数量:' . $result . '条');
        }

        return $this->asOk('五月以前【邮件记录】为空, 不需要删除');
    }
}